# -*-coding:utf-8 -*-
import xadmin
from xadmin import views
from django.conf import settings
from xadmin.util import sortkeypicker
from xadmin.views.dashboard import *
from django.urls import reverse
from datetime import datetime, timedelta
import core.treeplugin
from django.apps import apps

# 外部链接配置
ext_links = [
]

class MainDashboard(object):
    widgets = [
        [
            {"type": "list", "model": "content.News", 'title': u'最近资讯', 'count': 5, 'params': {'o': '-createdat'}},
            # {"type": "list", "model": "content.Notice", 'title': u'私有最新发布', 'count': 5, 'params': {'o': '-createdat', '_cols': 'f_icon.createdat', '_p_is_dir__exact': '0'}},
            # {"type": "addform", "model": 'core.note'}
        ],
        [
            #{"type": "qbutton", "title": "扩展链接", "btns": ext_links},
            {"type": "list", "model": 'xadmin.Log', 'title': u'最近操作', 'count': 5, 'params': {'o': '-action_time', '_cols': '__str__.user.action_time'}},
        ]
    ]

    def get_files_count(self):
        ctx = {}
        notify = apps.get_model(app_label='content', model_name="Notify")
        notice = apps.get_model(app_label='content', model_name="Notice")
        officedoc = apps.get_model(app_label='content', model_name="OfficeDoc")
        thirdparty = apps.get_model(app_label='content', model_name="ThirdParty")
        # notifymcls = apps.get_model(app_label='core', model_name="Notify")
        # linkmcls = apps.get_model(app_label='core', model_name="ExtLink")
        # notemcls = apps.get_model(app_label='core', model_name="Note")
        ctx['notify'] = notify.objects.order_by('-createdat').first()
        ctx['notice_count'] = notice.objects.count()
        ctx['officedoc_count'] = officedoc.objects.count()
        ctx['extlinks'] = thirdparty.objects.all()
        # ctx['pri_tops'] = primcls.objects.top_download(10, user=self.request.user)
        # ctx["privatefile_count"] = primcls.objects.filter(user=self.request.user).count()
        # ctx['pub_tops'] = pubmcls.objects.top_download(10)
        # ctx['pub_news'] = pubmcls.objects.top_new(10)
        # ctx["publicfile_count"] = pubmcls.objects.count()
        # ctx['notify'] = notifymcls.objects.order_by('-createdat').first()
        # ctx['extlinks'] = linkmcls.objects.all()
        # ctx['mynotes'] = notemcls.objects.top_recent(10, user=self.request.user)
        # ctx['today'] = datetime.today()
        # ctx['columns'] = [['col-sm-8']]  # 自己加的 无用测试数据， 后面需删掉

        return ctx

    def get_context(self):
        ctx = super(MainDashboard, self).get_context()
        ctx.update(self.get_files_count())
        # print("=================>", ctx)
        return ctx


xadmin.site.register(views.website.IndexView, MainDashboard)

admin_version = getattr(settings, "ADMIN_VERSION", "")
admin_title = getattr(settings, "XADMIN_TITLE", "KMS")
admin_short_title = getattr(settings, "XADMIN_SHORT_TITLE", "KMS")
licensed_to = getattr(settings, "LICENSED_TO", "成都拾贝科技有限公司")

class BaseSetting(object):
    enable_themes = True
    use_bootswatch = True
    admin_version = admin_version
    admin_short_title = admin_short_title
    admin_title = admin_title
    licensed_to = licensed_to
    site_title = admin_short_title


xadmin.site.register(views.BaseAdminView, BaseSetting)


class GlobalSetting(object):
    site_title = admin_short_title
    abrowser_base_template = "xadmin/abrowser_base_site.html"
    # version = getattr(settings, "VERSION", "1.0") # 注意名称冲突!
    # menu_style = 'accordion'

    def _test_abrowser(self):
        try:
            return self.request.META['HTTP_USER_AGENT'].find('7BYTE/ABrowser') >= 0
        except Exception:
            return False

    def init_request(self, *args, **kwargs):
        super(GlobalSetting, self).init_request(*args, **kwargs)
        return True

    def get_context(self):
        ctx = super(GlobalSetting, self).get_context()
        if self._test_abrowser():
            ctx['base_template'] = self.abrowser_base_template
            ctx["abrowser_agent"] = True
        return ctx

    def get_app_group(self):
        return None

    def get_ext_menu(self):
        return [
            #{'title': '帮助', 'icon': 'fa fa-question-circle', 'url': '/static/doc/index.html'},
            #{'title': '浏览器下', 'icon': 'fa fa-question-circle', 'url': reverse("browse_download")},
            #{'title': 'APP 下载', 'icon': 'fa fa-question-circle', 'url': reverse("apps_download")},
            {'title': 'API 文档', 'icon': 'fa fa-plug', 'url': reverse("restdocs:index")},
            # {'title': '系统发布日志', 'icon': 'fa fa-gift', 'url': reverse("xadmin:systempublishinfo")},
            {'title': '关于平台', 'icon': 'fa fa-info-circle', 'url': reverse("xadmin:about")},
            # {'title': '客户端测试', 'icon': 'fa fa-info-circle', 'url': "/static/doc/client_test.html"},
        ]

    @views.filter_hook
    def get_nav_menu(self):
        menus = super(GlobalSetting, self).get_nav_menu()
        for _menu in menus:
            if _menu['app'] == 'auth':
                _menu['title'] = "账户"
                _menu['order'] = 99
                _menu['icon'] = "fa fa-user"
            elif _menu['app'] == 'xadmin':
                _menu['title'] = "系统"
                _menu['order'] = 100
        ls = menus  # + custom_menus
        ls.sort(key=sortkeypicker(['order', 'app']))
        return ls


xadmin.site.register(views.CommAdminView, GlobalSetting)
